package com.dai.zhenfujin.http;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.dai.zhenfujin.AccountPasswordActivity;
import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.MainActivity;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.view.CustomLoadingDialog;
import com.google.gson.Gson;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/3/1.
 */
public class HttpClient {

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public static final String RET_CODE = "res_code";
    private static final String RET_CODE2 = "code";
    public static final String MESSAGE = "msg";
    public static final String RESULT = "res_hd";
    public static final String RESULT2 = "res_bd";

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static Handler handler;
    private static OkHttpClient okHttpClient;
    private static String path_url;
    /* public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //   .addInterceptor(basicParamsInterceptor) // 添加公共参数拦截器
            .addInterceptor(new LoggingInterceptor()) //添加okhttp日志拦截器
            .connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
            .writeTimeout(20, TimeUnit.SECONDS) //读取超时时间
            .readTimeout(20, TimeUnit.SECONDS) ////写入超时时间
            .retryOnConnectionFailure(false)//连接不上是否重连,false不重连
            .build();*/


    public static synchronized OkHttpClient getInstance(){
        if(okHttpClient == null){
            okHttpClient = new OkHttpClient.Builder()
                    //  .addInterceptor(basicParamsInterceptor) // 添加公共参数拦截器
                    .addInterceptor(new LoggingInterceptor()) //添加okhttp日志拦截器
                    // .sslSocketFactory(createSSLSocketFactory())//创建一个证书对象
                    // .hostnameVerifier(new TrustAllHostnameVerifier())//校验名称,这个对象就是信任所有的主机,也就是信任所有https的请求
                    .connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
                    .writeTimeout(20, TimeUnit.SECONDS) //读取超时时间
                    .readTimeout(20, TimeUnit.SECONDS) ////写入超时时间
                    .retryOnConnectionFailure(false)//连接不上是否重连,false不重连
                    .build();
            handler = new Handler(Looper.getMainLooper());
        }
        return okHttpClient;
    }




    public static void postImg(final Context context, String url, File file, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file_list", file.getName(),
                        RequestBody.create(MediaType.parse("image/png"), file));

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();


        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(() -> {
                    callBack.onFailure(4, e.getLocalizedMessage());
                    CustomLoadingDialog.dismiss(context);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context, response, callBack);
            }
        });
    }


    public static void postVideo(final Context context, String url, File file, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("videoFile", file.getName(),
                        RequestBody.create(MediaType.parse("video/mp4"), file));

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context, response, callBack);
            }
        });
    }


    public static void post(final Context context, String url, Map<String, Object> params, final CallBack callBack) {
        if (!EaseCommonUtils.isNetWorkConnected(context)) {
            UIUtils.showToastSafe("请检查网络连接");
            return;
        }
        if (url != Constants.EDITPRODUCT || url != Constants.ADDMSG)
        CustomLoadingDialog.show(context);
        path_url = url;
        Map<String, String> params2 = new HashMap<>();
        String token = SPUtils.getString(context, Constants.TOKEN);
        if (!TextUtils.isEmpty(token)) {
            params2.put("access_token", token);
        } else {
            params2.put("access_token", "");
        }
        params2.put("req_id", "");
        params2.put("device_code", "");
        params2.put("version", "android" + UIUtils.getVerName(context));
        params2.put("req_time", "");
        params.put("req_hd", params2);

        //表单提交 和 json 提交
        Gson gson = new Gson();
        String param = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, param);

      /*  FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            String key = map.getKey();
            Object value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            builder.add(key, (String) value);
        }*/

        //添加post公共请求参数  Constants.PACKAGE 和 Constants.CFROM
        //添加公共参数到 post 请求体
        //   RequestBody requestBody = builder.build();

        Logger.json(new Gson().toJson(params));

        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context, response, callBack);
            }
        });
    }


    public static String post2(final Context context, String url, Map<String, Object> params) {
        if (!EaseCommonUtils.isNetWorkConnected(context)) {
            UIUtils.showToastSafe("请检查网络连接");
            return null;
        }
        if (url != Constants.EDITPRODUCT || url != Constants.ADDMSG)
          //  CustomLoadingDialog.show(context);
        path_url = url;
        Map<String, String> params2 = new HashMap<>();
        String token = SPUtils.getString(context, Constants.TOKEN);
        if (!TextUtils.isEmpty(token)) {
            params2.put("access_token", token);
        } else {
            params2.put("access_token", "");
        }
        params2.put("req_id", "");
        params2.put("device_code", "");
        params2.put("version", "android" + UIUtils.getVerName(context));
        params2.put("req_time", "");
        params.put("req_hd", params2);

        //表单提交 和 json 提交
        Gson gson = new Gson();
        String param = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, param);

        Logger.json(new Gson().toJson(params));

        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        Response response = null;
        try {
            response = getInstance().newCall(request).execute();//得到Response 对象
            if (response.isSuccessful()){
                String json = response.body().string();
                Logger.json(json);
                return json;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void postRed(final Context context, String url, Map<String, String> params, final CallBack callBack) {
        if (!EaseCommonUtils.isNetWorkConnected(context)) {
            UIUtils.showToastSafe("请检查网络连接");
            return;
        }

        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            builder.add(key, value);
        }

        RequestBody requestBody = builder.build();

        Logger.json(new Gson().toJson(params));
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse2(context, response, callBack);
            }
        });
    }


    public static void get(Context context, String url, Map<String, String> map, final CallBack callBack) {
        System.out.println("===============================");
        if (map != null && map.size() > 0) {
            url += "&";
            for (String key : map.keySet()) {
                String value = map.get(key);
                url += key + "=" + value + "&";
            }
        }

        // 去掉最后一个空格
        //   url = url.substring(0, url.length() - 1);

        Request request = new Request.Builder()
                //.tag(tag)
                .url(url)
                .build();
        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(-1, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                handlerResponse2(context, response, callBack);
            }
        });
    }

    private static void handlerResponse2(final Context context, Response response, final CallBack callBack) throws IOException {
        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
        //json = json.replace("null", "\"\"");
        Logger.json(json);
        System.out.println("json==" + json);
        final String finalJson = json;
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(finalJson);
                    callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                    // int errCode2 = jsonObject.getInt(RET_CODE2);
                   /* if (errCode2 == 200 || errCode2 == 521 || errCode2 == 520) {
                    }else if (errCode2 == 201){
                        UIUtils.showToastSafe("红包发送失败");
                    }*/
                    CustomLoadingDialog.dismiss(context);
                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                    if (!TextUtils.isEmpty(e.getLocalizedMessage()))
                        if (e.getLocalizedMessage().contains("<html><head><title>")) {
                            UIUtils.showToastSafe("数据加载错误");
                        }
                    CustomLoadingDialog.dismiss(context);
                }
            }
        });
    }

    /**
     * 根据tag取消请求
     *
     * @param tag 标签
     */
    public static void cancelRequest(Object tag) {
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag)) {
                call.cancel();
            }
        }
    }


    private static void handlerResponse(final Context context, Response response, final CallBack callBack) throws IOException {
        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
        //json = json.replace("null", "\"\"");

        Logger.json(json);
        System.out.println("json==" + json);
        final String finalJson = json;
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (finalJson.contains(RESULT)) {
                        JSONObject jsonObject = new JSONObject(finalJson);
                        JSONObject json = jsonObject.getJSONObject(RESULT);
                        int res_code = json.getInt(RET_CODE);
                        String msg = json.getString(MESSAGE); //msg
                        if (res_code == 1) { //返回成功
                            if (finalJson.contains(RESULT2)) {
                                String result = jsonObject.getString(RESULT2);
                                if (path_url.equals(Constants.TYPELIST)){
                                    SPUtils.put(context,"json",result);
                                }
                                callBack.onSuccess(new Gson().fromJson(result, callBack.type));
                            }
                        } else if (msg.equals("用户资料没有完善")) {
                            String result = jsonObject.getString(RESULT);
                            callBack.onSuccess(new Gson().fromJson(result, callBack.type));
                            if (!msg.equals("非被找人，不需要扣费"))
                            UIUtils.showToastSafe(msg);
                        } else if (msg.equals("自己不能回复自己的评论")) {
                            String result = jsonObject.getString(RESULT2);
                            callBack.onSuccess(new Gson().fromJson(result, callBack.type));
                                UIUtils.showToastSafe(msg);
                        }else if (res_code == -9 ) { //|| res_code == 201
                          //  SPUtils.clear(context);
                         //   SPUtils.put(context,"welcome",false);
                          /*  if (Constants.PRODUCTLIST.equals(path_url) || Constants.TYPELIST.equals(path_url)){
                                return;
                            }*/
                            SPUtils.put(context,"login",false);
                            SPUtils.put(context,"welcome",true);
                            SPUtils.put(context, Constants.TOKEN, "");
                           // SPUtils.put(context,"login",false);
                            Intent intent = new Intent(context, AccountPasswordActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            context.startActivity(intent);
                        } else if (res_code == 201){  //无题
                            String result = jsonObject.getString(RESULT2);
                            callBack.onSuccess(new Gson().fromJson(result, callBack.type));
                            if (msg.contains("用户信息")) return;
                            UIUtils.showToastSafe(msg);
                        }else {
                            UIUtils.showToastSafe(msg);
                        }
                    }
                    CustomLoadingDialog.dismiss(context);

                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                    CustomLoadingDialog.dismiss(context);
                }
            }
        });
    }

    /**
     * 请求响应日志信息，方便debug
     */
    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Logger.i(String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
            if (null != chain) {
                Response response = chain.proceed(request);
                long t2 = System.nanoTime();

                Logger.i(String.format("Received response for %s in %.1fms%n%s",
                        response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                return response;
            }
            return null;
        }
    }
}
